package edu.snake.implement.view;


import edu.snake.core.model.arena.Arena;
import edu.snake.core.model.arena.Position;
import edu.snake.core.model.character.Character;
import edu.snake.implement.model.CharacterName;

import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;


public class ViewArena extends JPanel implements ActionListener {

    final UniversalRender universalRender;
    Arena arena;


    public ViewArena(int width, int height) {
        setFocusable(true);
        setPreferredSize(new Dimension(width, height));
        this.universalRender = new UniversalRender();
    }



    public void drawTextInArena(String s) {
        drawArena(this.arena);
        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metrics = getFontMetrics(small);
        Graphics g = this.getGraphics();
        g.setColor(Color.white);
        g.setFont(small);
        int stringHalfSize = metrics.stringWidth(s) / 2;
        int width = this.getWidth() / 2 - stringHalfSize;
        int height = this.getHeight() / 2;
        g.drawString(s, width, height);
    }


    public void actionPerformed(ActionEvent e) {
        arena = (Arena) e.getSource();
        drawArena(arena);
    }

    public void drawArena(Arena arena) {
        this.arena = arena;
        Iterator<Position> positionIterator = arena.iterator();
        while (positionIterator.hasNext()) {
            Position position = positionIterator.next();
            Character character = arena.get(position);
            CharacterName characterName;
            if (character == null) {
                characterName = CharacterName.EMPTY;
            } else {
                characterName = character.getName();
            }
            universalRender.render(position, characterName, this.getGraphics());

        }
    }

}
